using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;

namespace AzureDiagnostics2Excel
{
    public partial class CountersDownloadWindow : Form
    {
        public CountersDownloadWindow()
        {
            InitializeComponent();

            List<AccountSetting> accountSettings = new List<AccountSetting>();
            foreach (System.Configuration.SettingsProperty property in Properties.Settings.Default.Properties)
            {
                accountSettings.Add(new AccountSetting { AccountName = property.Name, ConnectionString = property.DefaultValue.ToString() });
            }
            this.comboBoxAccounts.DataSource = accountSettings;
            this.comboBoxAccounts.DisplayMember = "AccountName";
            this.comboBoxAccounts.ValueMember = "ConnectionString";

            this.textBoxFrom.Text = DateTime.UtcNow.AddMinutes(-20).ToString("yyyy-MM-dd HH:mm:ss");
            this.textBoxTo.Text = DateTime.UtcNow.AddMinutes(-10).ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            if (this.comboBoxAccounts.SelectedValue == null)
            {
                MessageBox.Show("Please select a valid Azure Table Storage Account.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (this.textBoxPerfCounters.Text == String.Empty || this.textBoxPerfCounters.Text == null)
            {
                MessageBox.Show("Please enter a list of performance counters.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.buttonLoad.Enabled = false;
            this.buttonLoad.Text = "Loading...";
            this.Activate();

            TableRepository repo = new TableRepository();

            Excel.Worksheet sheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet;

            DateTime from = DateTime.Parse(this.textBoxFrom.Text);
            DateTime to = DateTime.Parse(this.textBoxTo.Text);

            string[] perfCounterNames = this.textBoxPerfCounters.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

            IEnumerable<PerformanceCounterEntity> counters = repo.GetPerformanceCountersInTimeSpan(this.comboBoxAccounts.SelectedValue.ToString(), from, to);

            sheet.Cells[1, 1] = "Event Tick Count";
            sheet.Cells[1, 2] = "Deployment Id";
            sheet.Cells[1, 3] = "Role";
            sheet.Cells[1, 4] = "Role Instance";
            for (int i = 5; i <= (perfCounterNames.Count() + 4); i++)
            {
                sheet.Cells[1, i] = perfCounterNames[i - 5];
            }

            Excel.Range firstRow = (Excel.Range)sheet.Rows[1];
            firstRow.Columns.ColumnWidth = 20;
            firstRow.Font.Bold = true;
            // Fix first row
            sheet.Application.ActiveWindow.SplitRow = 1;
            sheet.Application.ActiveWindow.FreezePanes = true;
            // Now apply autofilter
            firstRow.AutoFilter(1,
                    System.Type.Missing,
                    Excel.XlAutoFilterOperator.xlAnd,
                    System.Type.Missing,
                    true);

            Excel.Range range = sheet.Cells[1, 1];
            DateTime prevEventDateTime = DateTime.Now;

            foreach (var counter in counters)
            {
                DateTime eventDateTime = new DateTime(counter.EventTickCount);
                eventDateTime = DateTime.Parse(eventDateTime.ToString("yyyy-MM-dd HH:mm:ss"));

                if (prevEventDateTime != eventDateTime)
                {
                    range = range.Offset[1, 0];
                }

                range.Value = eventDateTime;
                range.Offset[0, 1].Value = counter.DeploymentId;
                range.Offset[0, 2].Value = counter.Role;
                range.Offset[0, 3].Value = counter.RoleInstance;

                if (perfCounterNames.Contains(counter.CounterName))
                {
                    int columnIndex = Array.FindIndex(perfCounterNames, c => c == counter.CounterName) + 4;
                    range.Offset[0, columnIndex].Value = counter.CounterValue;
                }

                prevEventDateTime = eventDateTime;
            }

            this.Hide();
            this.buttonLoad.Text = "Load Formatted Data";
            this.buttonLoad.Enabled = true;

            MessageBox.Show("The Azure diagnostics data has been downloaded!", "Download Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
